'use strict';

const axios = require('axios');
const semver = require('semver');
const urlJoin = require('url-join');

module.exports = {
    getNpmInfo,
    getNpmVersion,
    getNpmSemverVersion,
    getDefaultRegistry,
    getNpmLatestVersion
};

function getNpmInfo(npmName, registry) {
    if(!npmName) {
        return null;
    }
    const registryUrl = registry || getDefaultRegistry();
    const npmInfoUrl = urlJoin(registryUrl, npmName);
    return axios.get(npmInfoUrl).then(response => {
        if(response.status === 200) {
            return response.data;
        } else {
            return null;
        }
    }).catch(err => {
        return Promise.reject(err);
    })
}

// 获取npm源 默认为淘宝源
function getDefaultRegistry(isOriginal = false) {
    return isOriginal ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org';
}

// 获取对应的npm包的版本号 返回一个版本号的数组
async function getNpmVersion(npmName, registry) {
    const data = await getNpmInfo(npmName, registry);
    if (data) {
        return Object.keys(data.versions);
    } else {
        return [];
    }
}


// 获取满足条件的版本号
function getNpmSemverVersions(baseVersion, versions) {
    return versions.filter(version => semver.satisfies(version,`^${baseVersion}`)).sort((a, b) => semver.gt(b, a));
}

 async function getNpmSemverVersion(baseVersion, npmName, registry) {
    const versions = await getNpmVersion(npmName, registry);
    const newVersions = getNpmSemverVersions(baseVersion, versions);
    if (newVersions && newVersions.length > 0) {
        return newVersions[0];
    }
}

async function getNpmLatestVersion(npmName, registry) {
    const versions = await getNpmVersion(npmName, registry);
    if (versions) {
        return versions.sort((a, b) => semver.gt(b, a))[0];
    } else {
        return null;
    }
}